package org.sam.swing.table.tools;

import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.Timer;

import org.sam.swing.JSPanelToolBar;
import org.sam.swing.resource.ResourceLoader;
import org.sam.swing.table.JSTableModel;
import org.sam.swing.table.TableModelStateChangeListener;
import org.sam.swing.table.TableModelStateEventObject;

/**
 * 表格操作状态栏
 * 
 * @author sam
 *
 */
public class JSTableStatusBar extends JSPanelToolBar implements TableModelStateChangeListener {

	private static final long serialVersionUID = 1291270347799081261L;

	/**
	 * 当前操作的tablemodel对象
	 */
	private JSTableModel<?> tableModel;

	/**
	 * 编辑状态对象
	 */
	private JLabel lblEdit;

	/**
	 * 系统提示栏
	 */
	private JLabel lblTip;

	/**
	 * 进度条
	 */
	private JProgressBar process;

	/**
	 * 时钟对象
	 */
	private Timer timer;

	/**
	 * 当前操作的tablemodel对象
	 * 
	 * @return
	 */
	public JSTableModel<?> getTableModel() {
		return tableModel;
	}

	/**
	 * 当前操作的tablemodel对象
	 * 
	 * @param tableModel
	 */
	public void setTableModel(JSTableModel<?> tableModel) {
		if (this.tableModel != tableModel) {

			if (this.tableModel != null) {
				this.tableModel.removeStateChangeListener(this);
			}

			if (tableModel != null) {
				tableModel.addStateChangeListener(this);
			}
		}
		this.tableModel = tableModel;
	}

	/**
	 * 当前操作的tablemodel对象
	 * 
	 * @param tableModel
	 */
	public JSTableStatusBar(JSTableModel<?> tableModel) {
		this.initCompents();
		this.setTableModel(tableModel);
	}

	/**
	 * 初始化控件显示
	 */
	private void initCompents() {
		this.setLayout(new FlowLayout(FlowLayout.LEFT, 3, 3));
		lblEdit = new JLabel(new ImageIcon(ResourceLoader.getResource(ResourceLoader.IMAGE_MODIFY)));
		lblEdit.setPreferredSize(new Dimension(16, 16));
		lblEdit.setVisible(false);
		this.add(lblEdit);

		process = new JProgressBar();
		process.setPreferredSize(new Dimension(125, 16));
		process.setVisible(false);
		this.add(process);

		lblTip = new JLabel("");
		lblTip.setVisible(false);
		this.add(lblTip);
		
		this.process.setMinimum(1);
		this.process.setMinimum(1000);

		//进度条
		timer = new Timer(100, e -> {
			process.setValue(process.getValue() + 1);
		});
	}

	/**
	 * 当tablemodel发生改变的时候执行的操作
	 */
	@Override
	public void stateChanged(TableModelStateEventObject e) {
		if (e == null)
			return;
		
		switch(e.getState()){
		case EDITABLE:
			lblEdit.setVisible((Boolean) e.getAfterValue());
			break;
		case ONPROCESS:
			this.process.setValue(1);
			this.lblTip.setText(e.getAfterValue() == null ? "" : e.getAfterValue().toString());
			this.process.setVisible(true);
			this.lblTip.setVisible(true);
			this.timer.start();
			break;
		case ENDPROCESS:
			this.timer.stop();
			this.process.setVisible(false);
			this.lblTip.setVisible(false);
			break;
		}

	}
}
